/*
 * Copyright (C) 2010, Funcom AS, All Rights Reserved
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  @authors
 *  Svein Gunnar Larsen <sveingunnarlarsen@gmail.com>
 *  Erik Thune Lund <culex.eriklund@gmail.com>
 *  Michel Krohn-Dale <kronicz@gmail.com>
 */

package com.funcom.peeler.utils;

import java.io.File;
import java.util.regex.Pattern;

public class RelativePath {

    /**
     * Helper function to make path relative
     * @param target File path of selected file
     * @param base File path to root
     * @return returns the path relative to the base path
     */
    public static File getRelativeFile(File target, File base)
    {
        String[] baseComponents = base.getAbsolutePath().split(Pattern.quote(File.separator));
        String[] targetComponents = target.getAbsolutePath().split(Pattern.quote(File.separator));

        // skip common components
        int index = 0;
        for (; index < targetComponents.length && index < baseComponents.length; ++index)
        {
            if (!targetComponents[index].equals(baseComponents[index]))
                break;
        }

        StringBuilder result = new StringBuilder();
        if (index != baseComponents.length)
        {
            // backtrack to base directory
            for (int i = index; i < baseComponents.length; ++i)
                result.append(".." + File.separator);
        }
        for (; index < targetComponents.length; ++index)
            result.append(targetComponents[index] + File.separator);
        if (!target.getPath().endsWith("/") && !target.getPath().endsWith("\\"))
        {
            // remove final path separator
            result.delete(result.length() - "/".length(), result.length());
        }
        return new File(result.toString());
    }
}
